package control;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import server.EchoServer;
import server.mysqlConnection;







/**
 * @author Shay
 *   This class responsible for the operation Borrow, when the client wants to activate this operation he inserts data in the GUI client
,the data we insert into array string that will send to the server, In the server we maps the message by checking the first string (see AbstractControl).*/

public class BorrowControl extends AbstractControl
{
	private int bidToCheck;
	private int copyToCheck;
	@Override
	

	
	
	public Object anlyze(String[] msg) 
	{
		ArrayList<Object> s=new ArrayList<Object>();
		s.add("borrow");
		bidToCheck=Integer.parseInt(msg[1]);
		copyToCheck=Integer.parseInt(msg[3]);
		if (sidIsExistAndActive(msg[2])) 
		{
			if (checkExist()) 
			{
				if (isInSaveOrderList(msg[2]) || (!isBorrwed(msg[1], msg[3]) && !isOrdered()))
				{
					if(!alreadyHaveACopy(msg[1],msg[2]))
					{
							Calendar returnDate = Calendar.getInstance();
							if (bookIsPopular(msg[1], msg[3])) //We check if this book is popular and by that we decide what would be the expected return date
							{
								returnDate.add(Calendar.DATE, 3);
							} else
								returnDate.add(Calendar.DATE, 14);
							DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd");
							Calendar cal = Calendar.getInstance();
							String today = new String("'");
							today += dateFormat.format(cal.getTime());
							today += "'";
							String returnD = "'"
								+ dateFormat.format(returnDate.getTime()) + "'";
							String query;
							if(isBorrowToday(msg[2],today))
							{
								query = new String("update test.borrow set returnDate='00/00/00'"+"WHERE sid="+msg[2]+" and bid="+bidToCheck+" and copy="+copyToCheck+" and borrowDate="+today);
							}
							else
							{
								query = new String("insert into test.borrow set "
										+ "bid=" + msg[1] + ",sid=" + msg[2]
										+ ",borrowDate=" + today + ", expectedReturnDate="
										+ returnD + ", copy=" + msg[3] + ";");	
							}
								String rst = mysqlConnection.update(query);
								mysqlConnection.update("update books set expectedReturnDate="+returnD+" where bid="+msg[1]+" and copy="+msg[3]);
								s.add(rst);
								mysqlConnection.update("update books set isborrowed=1 where bid="+msg[1]+" and copy="+msg[3]);
								logActivity(msg[2],msg[0]+" "+getNameBook(msg[1])+" "+msg[1]+"-"+msg[3]);
								return s;
					}
					s.add(new String("You alreay have this book"));
				} 
				else
					s.add(new String("This book copy is borrowed"));
				return s;
			}
			s.add(new String("No such title or such copy!!!"));
		}
		else
			s.add(new String("No Such Subscriber or inactive!!!"));
		return s;
	}

	private boolean isBorrowToday(String sid, String today) 
	{
		String key=new String("Select sid from test.borrow WHERE sid="+sid+" and bid="+bidToCheck+" and copy="+copyToCheck+" and borrowDate="+today);
		String[][] rst=mysqlConnection.select(key,1);
		if(rst.length>0) 
			return true;
		return false;
	}

	/**
	 * @param sid
	 * @return
	 * //We check if this subscriber Appears in table SaveOrderList in DB
	 */
	private boolean isInSaveOrderList(String sid) 
	{
		String rst=mysqlConnection.check("Select * from saveorderlist WHERE bid="+bidToCheck+" AND sid="+sid+" and copy="+copyToCheck);
		if(!(rst.compareTo("NotEXIST")==0) && !(rst.compareTo("FAIL")==0)) 
		{
			mysqlConnection.update("DELETE from saveorderlist WHERE bid="+bidToCheck+" AND sid="+sid+" and copy="+copyToCheck);		
			return true;
		}
		return false;
	}

	/**
	 * Check if this book have orders
	 * @return true/false
	 */
	private boolean isOrdered() 
	{
		return (!EchoServer.bookOrdersQueue.get(bidToCheck).isEmpty());
	}

	/**
	 * We check if this subscriber Appears in table SaveOrderList in DB
	 * @param sid
	 * @return true/false
	 */
	private boolean sidIsExistAndActive(String sid) 
	{
		String key=new String("Select CardStatus from Subscriber WHERE sid="+sid);
		String[][] rst=mysqlConnection.select(key,1);
		if(rst.length>0 && rst[0][0].compareTo("1")==0) 
			return true;
		return false;
	}


	
	/**
	 * We check if this subscriber have already this book copy
	 * @param bid
	 * @param sid
	 * @return true/false
	 */
	private boolean alreadyHaveACopy(String bid,String sid) 
	{
		String[][] rst=mysqlConnection.select("Select returnDate from test.borrow WHERE bid="+bid+" AND sid="+sid,1);
		for(int i=0;i<rst.length;i++)
		{
			if(rst[i][0].compareTo("00/00/00")==0)
			{
				return true;
			}
		}
		return false;
	}

	public Boolean checkExist() 
	{
		String rst=mysqlConnection.check("select * from books WHERE bid="+bidToCheck+" AND copy="+copyToCheck);
		if(rst.compareTo("NotEXIST")==0 || rst.compareTo("FAIL")==0) 
			return false;
		return true;
	}
	
	
	/**
	 * We check if this book is already borrowed by someone
	 * @param bid
	 * @param copy
	 * @return true/false
	 */
	private boolean isBorrwed(String bid,String copy)
	{
		String key=new String("Select isborrowed from books WHERE bid=" +bid+" AND copy="+copy);
		String[][] rst=mysqlConnection.select(key,1);
		if(rst.length!=0 && rst[0][0].compareTo("1")==0) 
			return true;
		return false;
		
	}

}
